<script setup lang="ts">
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import CustomNavbar from '@/pages/index/componets/CustomNavbar.vue'
import CategoryPanel from '@/pages/index/componets/CategoryPanel.vue'
import HotPanel from '@/pages/index/componets/HotPanel.vue'
import PageSkeleton from '@/pages/index/componets/PageSkeleton.vue'
import { useGuessList } from '@/composables'

const bannerList = ref<BannerItem[]>([])
/**
 * 获取首页轮播图
 */
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}
const category = ref<CategoryItem[]>([])
/**
 * 获取首页分类
 */
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  category.value = res.result
}
const hotlist = ref<HotItem[]>([])
/**
 * 获取热门数据
 */
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  hotlist.value = res.result
}
// 导入封装的组合api 猜你喜欢调用方法
const { guessRef, onScrolltolower } = useGuessList()

const isTriggered = ref(false)
/**
 * 首页下拉刷新
 */
const onRefresh = async () => {
  isTriggered.value = true
  // 先重置`猜你喜欢组件`的数据，在重置获取
  guessRef.value?.resetData()
  // 性能优化 使用 Promise.all 可以并发请求数据，
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getMore(),
  ])
  isTriggered.value = false
}
// 加载判断
const isLoadding = ref(false)
onLoad(async () => {
  isLoadding.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoadding.value = false
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar></CustomNavbar>
  <scroll-view
    @scrolltolower="onScrolltolower"
    @refresherrefresh="onRefresh"
    :refresher-triggered="isTriggered"
    refresher-enabled
    class="scroll-view"
    scroll-y
  >
    <PageSkeleton v-if="isLoadding" />
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 首页分类 -->
      <CategoryPanel :list="category" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotlist" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
